import tkinter as tk
import random

class RandomColorBlocks:
    def __init__(self, _root):
        self.root = _root
        self.root.title("随机色块生成器")
        self.root.resizable(width=False, height=False)

        # 创建可透明窗口
        self.alpha_window = tk.Toplevel(self.root, bg='white')
        self.alpha_window.title("色块")
        self.alpha_window.geometry("104x104")
        self.alpha_window.overrideredirect(True)
        self.alpha_window.resizable(False, False)

        # 在可透明窗口创建画布用于显示色块
        self.canvas = tk.Canvas(self.alpha_window, width=100, height=100, bg='white')
        self.canvas.pack()

        # 创建刷新按钮
        self.button = tk.Button(self.root, text="刷新色块", command=self.generate_blocks)
        self.button.pack(side="left", padx=10, pady=(200, 5))

        # 创建Spinbox并绑定验证函数
        vcmd = (self.root.register(self.validate_spinbox), '%P')
        tk.Label(self.root, text="透明度(0% - 100%):").pack(side="left", pady=(200, 5))
        self.alpha_var = tk.IntVar(value=0)
        self.input = tk.Spinbox(self.root, from_=0, to=100, textvariable=self.alpha_var, width=5, state="normal",
                                validate="key", validatecommand=vcmd)
        self.input.pack(side="left", padx=10, pady=(200, 5))

        # 绑定窗口事件
        self.root.bind("<Configure>", self.on_root_move) # 窗口移动时
        self.root.bind("<Unmap>", self.on_minimize)  # 窗口最小化时
        self.root.bind("<Map>", self.on_restore)  # 窗口恢复时

        # 绑定焦点事件
        self.input.bind("<FocusOut>", self.focus_out_validation) # 确保Spinbox最终值在范围内

        # 初始生成色块
        self.generate_blocks()

    def validate_spinbox(self, P):
        """验证Spinbox输入是否在0-100之间"""
        if P == "":
            return True  # 允许空输入（用户可能正在删除内容）

        try:
            value = int(P)
            if 0 <= value <= 100:
                return True
            else:
                return False
        except ValueError:
            return False

    def focus_out_validation(self, event):
        """当Spinbox失去焦点时，确保值在有效范围内"""
        try:
            value = int(self.input.get())
            if value < 0:
                self.alpha_var.set(0)
            elif value > 100:
                self.alpha_var.set(100)
        except ValueError:
            # 如果输入不是数字，恢复为0
            self.alpha_var.set(0)

        # 更新透明度
        self.alpha_window.attributes("-alpha", (100 - self.alpha_var.get()) / 100)

    def on_root_move(self, event):
        """当主窗口移动时，调整Toplevel窗口位置"""
        if event.widget == self.root:
            x = self.root.winfo_x() + 89
            y = self.root.winfo_y() + 75
            self.alpha_window.geometry(f"+{x}+{y}")
            self.alpha_window.lift()  # 确保色块窗口在最上面

    def on_minimize(self, event):
        """当主窗口最小化时，隐藏Toplevel窗口"""
        self.alpha_window.withdraw()

    def on_restore(self, event):
        """当主窗口恢复时，显示Toplevel窗口"""
        self.alpha_window.deiconify()
        # 更新Toplevel窗口位置
        x = self.root.winfo_x() + 89
        y = self.root.winfo_y() + 75
        self.alpha_window.geometry(f"+{x}+{y}")
        self.alpha_window.lift()  # 确保色块窗口在最上面

    def generate_blocks(self):
        """生成随机色块"""
        # 清除画布上的所有元素
        self.canvas.delete("all")

        # 生成随机颜色
        color = self.generate_random_color()

        # 在画布上创建矩形色块
        self.canvas.create_rectangle(0, 0, 101, 101, fill=color, outline=color)

    def generate_random_color(self):
        """生成随机颜色"""
        # 生成随机的RGB值
        r = random.randint(0, 255)
        g = random.randint(0, 255)
        b = random.randint(0, 255)

        if self.alpha_var.get() != 0:
            self.alpha_window.attributes("-alpha", (100 - self.alpha_var.get()) / 100)

        # 将RGB值转换为十六进制颜色代码
        return f"#{r:02x}{g:02x}{b:02x}"


# 创建主窗口
if __name__ == "__main__":
    root = tk.Tk()
    app = RandomColorBlocks(root)
    root.mainloop()